package com.studentEasyui.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.studentEasyui.entity.StudentEntity;
import com.studentEasyui.service.StudentService;
import com.studentEasyui.util.JsonUtil;


import jdk.nashorn.internal.runtime.GlobalConstants;


public class StudentServlet extends HttpServlet {
	StudentService  studentService;
	private static final long serialVersionUID = 1L;
	private static ObjectMapper mapper = new ObjectMapper();
	ApplicationContext applicationContext;
	@Override
	public void init() throws ServletException {
		//Spring容器
		applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
				//通过容器获取Bean
		studentService = applicationContext.getBean("studentServiceImpl",StudentService.class);
	}

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		arg0.setCharacterEncoding("UTF-8");
		arg1.setCharacterEncoding("UTF-8");
		String method=arg0.getParameter("method");
		if ("add".equals(method)) {
			add(arg0, arg1);
		} else if ("delete".equals(method)) {
			delete(arg0, arg1);
		} else if ("edit".equals(method)) {
			edit(arg0, arg1);
		} else if ("update".equals(method)) {
			update(arg0, arg1);
		} else if ("query".equals(method)) {
			query(arg0, arg1);
		} else if ("login".equals(method)) {
			login(arg0, arg1);
		}
	}

	private void add(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");
		StudentEntity student = JsonUtil.jsonToBean(strJson, StudentEntity.class);
		studentService.addStudent(student);
		
	}

	private void delete(HttpServletRequest arg0, HttpServletResponse arg1) {
		String ids = arg0.getParameter("ids");
		if (ids != null && ids.trim() != "") {
			studentService.deleteStudent(Long.valueOf(ids));
			arg1.getWriter().print(JsonUtil.beanToJson(new Result()));
		} else {
			arg1.getWriter().print(JsonUtil.beanToJson(new Result("0", "参数错误")));
		}
		
	}

	private void edit(HttpServletRequest arg0, HttpServletResponse arg1) {
		Long id = Long.valueOf(arg0.getParameter("id"));
		List<StudentEntity> list = studentService.listAll();
		for (StudentEntity user : list) {
			if (user.getId().equals(id)) {
				StudentEntity userId = user;
				PrintWriter out = arg1.getWriter();
				out.print(mapper.writeValueAsString(userId));
				break;
			}
		}
		
	}

	private void update(HttpServletRequest arg0, HttpServletResponse arg1) {
		String strJson = arg0.getParameter("data");// 解析
		StudentEntity student = JsonUtil.jsonToBean(strJson, StudentEntity.class);
		Long id = student.getId();
		String name = student.getName();
		String idNumber = student.getIdNumber();
		String age = student.getAge();
		String phone = student.getPhone();
		String address = student.getAddress();
		String censusRegister = student.getCensusRegister();
		
		
		StudentEntity stu = new StudentEntity();
		studentService.updateStudent(stu);
//		
//		String strJson = arg0.getParameter("data");// 解析
//		User userInfo = JsonUtil.jsonToBean(strJson, User.class);
//		Long id = userInfo.getId();
//		String departmentNum = userInfo.getDepartmentNum();
//		String userNum = userInfo.getUserNum();
//		String password = userInfo.getPassword();
//		String createName = userInfo.getCreateName();
//		String updateName = userInfo.getUpdateName();
//		User user = new User(id, departmentNum, userNum, password, createName, updateName);
//		userService.update(user);
		
	}

	private void query(HttpServletRequest arg0, HttpServletResponse arg1) {
		StudentEntity student = new StudentEntity();
		student.setName("name");
		student.setIdNumber("idNumber");
		student.setAge("age");
		student.setPhone("phone");
		student.setAddress("address");
		student.setCensusRegister("censusRegister");
		student.setCandiCar("candiCar");
		student.setSchool("school");
		student.setLearnSalary("learnSalary");
		student.setCreateName("createName");
		student.setDeleleLogo("deleleLogo");
		List<StudentEntity> shopList = studentService.listAll();
		shopList.forEach(System.out::println);

	}

	private void login(HttpServletRequest arg0, HttpServletResponse arg1) {
		String name = arg0.getParameter("name");
		String idNumber = arg0.getParameter("idNumber");
		StudentEntity student = new StudentEntity(name,idNumber);
		String verifyCode = arg0.getParameter("VerificationCode");
		String sessionVerifyCode = (String) arg0.getSession(true).getAttribute(verifyCode);
		if (sessionVerifyCode != null && sessionVerifyCode.equals(verifyCode)) {
			arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
			return;
		}
		List<StudentEntity> list = studentService.getById(student);
		if (list != null) {
			list.forEach(e -> {
				if (e.getName() != null && !e.getName().equals("") && e.getIdNumber() != null
						&& !e.getIdNumber().equals("")) {
					arg0.getSession().setAttribute(GlobalConstants.SESSION_USER, name);
					try {
						arg1.sendRedirect("index.jsp");
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				} else {
					arg0.setAttribute("msg", "用户名或密码错误");
					try {
						arg0.getRequestDispatcher("login.jsp").forward(arg0, arg1);
					} catch (ServletException e1) {
						e1.printStackTrace();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			});
		}
	}
}
